﻿using System;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;

namespace DotNetStar.TheKing.Domain.EventHandlers
{
    using SDDP;
    using Infrastructure;

    public class NotificationEventHandler : EventHandlerBase<NotificationEventHandler>, 
        IEventHandler<ContentReplyNotificationEvent>
    {
        private readonly IStorage<User, long> _userStorage;
        private readonly IStorage<Content, long> _contentStorage;
        private readonly NotificationSchedular _notificationSchedular;
        public NotificationEventHandler(
            IStorage<User, long> userStorage,
            IStorage<Content,long> contentStorage,
            NotificationSchedular notificationSchedular,
            ILoggerFactory loggerFactory, 
            IMemoryCache memoryCache) 
            : base(loggerFactory, memoryCache)
        {
            _contentStorage = contentStorage;
            _userStorage = userStorage;
            _notificationSchedular = notificationSchedular;
        }

        public void Handle(ContentReplyNotificationEvent e)
        {
            if (e == null)
            {
                throw new ArgumentNullException(nameof(e));
            }

            NotificationHandler(e);
        }

        private void NotificationHandler(NotificationBaseEvent e)
        {
            if (e == null)
            {
                throw new ArgumentNullException(nameof(e));
            }



            if ((e.Notification is SmsNotification && !e.User.MobileConfirmed) )
            {
                base.GetLogger.LogWarning("用户({0})的手机号没有激活，不会发送通知给当前手机({1})", e.User.UserName, e.User.Mobile);
                return;
            }

            if ((e.Notification is EmailNotification && !e.User.EmailConfirmed))
            {
                base.GetLogger.LogWarning("用户({0})的邮箱没有激活，不会发送通知给当前邮箱({1})", e.User.UserName, e.User.Email);
                return;
            }

            _notificationSchedular.CreateNotification(e.Notification);
        }
    }
}
